package cn.darkhorse.mesadmin.controller.system;

import cn.darkhorse.messystem.dto.MesUserDTO;
import cn.darkhorse.messystem.service.IMesSysPostService;
import com.github.pagehelper.Page;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author yuanjun
 * @since 2022/11/11 13:52
 */
@RestController
@RequestMapping("/mes/user")
public class MesUserController extends BaseController {

    @Resource
    private ISysUserService iSysUserService;
    @Resource
    private IMesSysPostService iMesSysPostService;
    @Resource
    private ISysDeptService iSysDeptService;
    @Resource
    private SysDeptMapper sysDeptMapper;
    @Resource
    private RedisCache redisCache;
    @Autowired
    private ISysPostService postService;
    @Resource
    private SysUserMapper sysUserMapper;


    /**
     * 根据部门id获取该部门和该部门下属部门所有未停用的用户
     * @param deptId 部门id
     * @return
     */
    @RequestMapping("/list")
    public TableDataInfo getUsers(Long deptId, String nickName) {
        startPage();
        SysUser sysUser = new SysUser();
        sysUser.setDeptId(deptId);
        sysUser.setNickName(nickName);
        sysUser.setDelFlag("0");
        sysUser.setStatus("0");
        List<SysUser> sysUsers = iSysUserService.selectUserList(sysUser);

        // 去掉被停用的用户
        Iterator<SysUser> iterator = sysUsers.iterator();
        while (iterator.hasNext()) {
            SysUser next = iterator.next();
            if (!next.getDelFlag().equals("0")) {
                iterator.remove();
            }
        }


        // 获取用户岗位
        Map<String, String> postMap = iMesSysPostService.getUserPosts();

        // 获取部门信息
        List<SysDept> deptList = iSysDeptService.selectDeptList(new SysDept());
        Map<Long,String> deptMap = new HashMap<>();
        for (SysDept dept :
                deptList) {
            deptMap.put(dept.getDeptId(), dept.getDeptName());
        }

        // 组合返回结果
        Page<MesUserDTO> resultList = new Page<>();
        if(sysUsers instanceof Page) {
            resultList.setTotal(((Page) sysUsers).getTotal());
        }else {
            resultList.setTotal(sysUsers.size());
        }
        for (SysUser user :
                sysUsers) {
            String deptName = deptMap.get(user.getDeptId());
            String postName = postMap.get(user.getUserName());
            MesUserDTO userDTO = new MesUserDTO();
            userDTO.setId(user.getUserId())
                    .setDeptId(user.getDeptId())
                    .setDeptName(deptName)
                    .setNickName(user.getNickName())
                    .setPostNames(postName)
                    .setUserName(user.getUserName());
            resultList.add(userDTO);
        }

        return getDataTable(resultList);
    }
   /* @RequestMapping("/listall")
    public AjaxResult getUsersAll() {
        List<SysUser> sysUsers = sysUserMapper.selectUserListNoAuth(new SysUser());
        return AjaxResult.success(sysUsers);
    }*/
    /**
     * 获取制单人制单部门实时信息
     * @param userId
     * @return
     */
    @RequestMapping("/getUser")
    public AjaxResult getUser(Long userId){
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if(null==userId){
            userId=user.getUserId();
        }
        AjaxResult ajax = AjaxResult.success();
        SysUser sysUser = iSysUserService.selectUserById(userId);
        List<SysDept> sysDepts = sysDeptMapper.selectDeptListNoAuth(new SysDept());
        Map<Long, String> deptMap = new HashMap<>();
        Iterator<SysDept> iterator = sysDepts.iterator();
        while (iterator.hasNext()) {
            SysDept dept = iterator.next();
            deptMap.put(dept.getDeptId(), dept.getDeptName());
        }
        Map<Long, String> resultMap = new HashMap<>();
        for (SysDept dept :
                sysDepts) {
            if (dept.getParentId().equals(0L)) {
                continue;
            }
            String[] split = (dept.getAncestors() + "," + dept.getDeptId().toString()).split(",");

            StringBuilder deptFullName = new StringBuilder();
            for (int i = 1; i < split.length; i++) {
                deptFullName.append(deptMap.get(Long.valueOf(split[i]))).append("/");
            }
            resultMap.put(dept.getDeptId(),deptFullName.substring(0,deptFullName.length() - 1).toString());
        }
        resultMap.entrySet().forEach(item->{
            if (sysUser.getDeptId().equals(item.getKey())) {
                ajax.put("deptName",item.getValue());
            }
        });
        ajax.put("userId",sysUser.getUserId());
        ajax.put("userName",sysUser.getUserName());
        ajax.put("nickName",sysUser.getNickName());
        ajax.put("dept",sysUser.getDeptId());
        return ajax;
    }

    @RequestMapping(value = "/logout-force",method = RequestMethod.POST)
    public AjaxResult logOutForce(Long userId){
        Collection<String> keys = redisCache.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
        boolean result=false;
        for (String key : keys){
            LoginUser user = redisCache.getCacheObject(key);
            if(user.getUserId().equals(userId)){
                result = redisCache.deleteObject(CacheConstants.LOGIN_TOKEN_KEY + user.getToken());
            }
        }
        return AjaxResult.success(result);
    }

    @RequestMapping("/getUserPosts")
    public AjaxResult getUserPosts(Long userId){
        List<SysPost> sysPosts = postService.selectPostAll();
        Map<Long,String> postMap=sysPosts.stream().collect(Collectors.toMap(SysPost::getPostId,SysPost::getPostName));
        List<Long> postIds = postService.selectPostListByUserId(userId);
        List<String> postNames=new ArrayList<>();
        if(null!=postIds&&postIds.size()>0){
            for (Long postId : postIds) {
                if(postMap.containsKey(postId)){
                    postNames.add(postMap.get(postId));
                }
            }
        }
        return AjaxResult.success(StringUtils.join(postNames, ","));
    }
}
